<template>
  <div>
    <el-row :gutter="10">
      <el-col :span="1.5">
        <el-button
          type="primary"
          v-hasPermi="['21210']"
          plain
          icon="el-icon-plus"
          @click="handleAdd"
          >设置试卷</el-button
        >
      </el-col>

      <!-- 搜索  关键字：手机号+姓名 -->
      <el-form
        :model="queryParams"
        ref="queryForm"
        v-show="showSearch"
        :inline="true"
        label-width="80px"
      >
        <el-form-item label="关键字" prop="keywords">
          <el-input
            v-model="queryParams.keywords"
            placeholder="请输入试卷名称/发布人"
            clearable
            style="width: 240px"
            @keyup.enter.native="handleQuery"
            size="small"
          />
        </el-form-item>
        <el-form-item>
          <el-button
            type="primary"
            icon="el-icon-search"
            size="mini"
            @click="handleQuery"
            >搜索</el-button
          >
          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
            >重置</el-button
          >
        </el-form-item>
      </el-form>
    </el-row>

    <el-table
      v-loading="loading"
      :data="tableList"
      :border="true"
      style="margin-top: 0"
    >
      <!-- <el-table-column align="center" prop="img" label="试卷图片" width="240">
        <template slot-scope="scope">
          <img :src="scope.row.img" width="200" height="100" />
        </template>
      </el-table-column> -->
      <el-table-column
        label="试卷名称"
        prop="title"
        align="center"
        :show-overflow-tooltip="true"
        width="160"
      >
        <template slot-scope="scope">
          <span @click="handleSee(scope.row)" class="active">
            {{ scope.row.title }}
          </span>
        </template>
      </el-table-column>
      <el-table-column
        align="center"
        prop="duration"
        label="答题时长"
      />
      <el-table-column
        label="试题数量"
        prop="theNum"
        align="center"
      ></el-table-column>
      <el-table-column
        label="试卷类型"
        align="center"
        width="170"
      >
        <template slot-scope="scope">
          <span v-if="scope.row.typeVal === 1">随机试题</span>
          <span v-if="scope.row.typeVal === 2">固定试题</span>
        </template>
      </el-table-column>
      <el-table-column
        label="试卷总分"
        prop="totalScore"
        align="center"
        :show-overflow-tooltip="true"
      />
      <el-table-column
        label="及格分数"
        prop="passLine"
        align="center"
        :show-overflow-tooltip="true"
      />
      <el-table-column label="归档" align="center" key="enable">
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.enable"
            :active-value="1"
            :inactive-value="0"
            @change="handleStatusChange(scope.row)"
          ></el-switch>
        </template>
      </el-table-column>
      <el-table-column
        label="录入时间"
        prop="releaseTime"
        align="center"
        :show-overflow-tooltip="true"
      />
      <el-table-column
        label="发布人"
        prop="publisher"
        align="center"
        :show-overflow-tooltip="true"
      />
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
        fixed="right"
        width="100"
      >
        <template slot-scope="scope">
          <div v-if="scope.row.enable === 0">
            <el-button
              size="mini"
              type="text"
              v-hasPermi="['21220']"
              @click="handleUpdate(scope.row)"
              >修改</el-button
            >
            <el-button
              size="mini"
              type="text"
              v-hasPermi="['21230']"
              @click="handleDelete(scope.row)"
              >删除</el-button
            >
          </div>
        </template>
      </el-table-column>
    </el-table>
    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.currentPage"
      :limit.sync="queryParams.pagesize"
      @pagination="getList"
    />
    <!-- 添加或修改角色配置对话框 -->
    <el-dialog
      class="form-div"
      :title="title"
      :visible.sync="open"
      width="700px"
      append-to-body
    >
      <el-form
        ref="form"
        :model="form"
        :rules="rules"
        :validate-on-rule-change="false"
        label-width="140px"
      >
        <!-- *试卷名称、*【选择题库】（多级下拉框）、*试卷类型（固定试题、随机试题）、*答卷时长、*单选题数量和分值、多选题数量和分值、*判断题数量和分值、*填空题数量和分值、试卷总分（自动计算）、*及格分数 -->
        <!-- <el-form-item label="*试卷图片" prop="img">
          <uploadImage v-model="form.img" />
        </el-form-item> -->
        <el-form-item label="试卷名称" prop="title">
          <el-input v-model="form.title" placeholder="请输入试卷名称" />
        </el-form-item>
        <el-form-item label="试题分类" prop="questionCategoryId">
          <treeselect
            v-model="form.questionCategoryId"
            :options="treeOptions"
            :show-count="true"
            @select="selectTree"
            @input="inputTree"
            placeholder="请选择试题分类"
          />
        </el-form-item>
        <el-form-item label="答题时长" prop="duration">
          <el-input v-model="form.duration" placeholder="请输入答题时长">
            <template slot="append">分钟</template>
          </el-input>
        </el-form-item>
        <el-form-item label="试卷类型" prop="typeVal">
          <el-radio-group v-model="form.typeVal" @change="changeTypeVal">
            <el-radio :label="1">随机试题</el-radio>
            <!-- @click.native.prevent="handleColumnsConfig" -->
            <el-radio :label="2" @click.native.prevent="handleColumnsConfig"
              >固定试题</el-radio
            >
          </el-radio-group>
        </el-form-item>
        <el-form-item label="单选题数量和分值" prop="singleNum" class="side">
          <!-- form.singleNum -->
          <el-input
            v-model="form.singleNum"
            type="number"
            placeholder="单选题数量"
            @input="changScore"
            min="0"
            :disabled="form.typeVal === 2"
          />
          <el-input
            v-model="form.singleVal"
            @input="changScore"
            type="number"
            placeholder="单选题分值"
            min="0"
          />
        </el-form-item>
        <el-form-item label="多选题数量和分值" prop="multipleNum" class="side">
          <el-input
            v-model="form.multipleNum"
            type="number"
            placeholder="多选题数量"
            @input="changScore"
            min="0"
            :disabled="form.typeVal === 2"
          />
          <el-input
            v-model="form.multipleVal"
            @input="changScore"
            type="number"
            placeholder="多选题分值"
            min="0"
          />
        </el-form-item>
        <el-form-item label="判断题数量和分值" prop="judgNum" class="side">
          <el-input
            v-model="form.judgNum"
            type="number"
            placeholder="判断题数量"
            @input="changScore"
            min="0"
            :disabled="form.typeVal === 2"
          />
          <el-input
            v-model="form.judgVal"
            @input="changScore"
            type="number"
            placeholder="判断题分值"
            min="0"
          />
        </el-form-item>
        <el-form-item
          label="填空题数量和分值"
          prop="completionNum"
          class="side"
          min="0"
          :disabled="form.typeVal === 2"
        >
          <el-input
            v-model="form.completionNum"
            type="number"
            placeholder="填空题数量"
            @input="changScore"
            min="0"
          />
          <el-input
            v-model="form.completionVal"
            @input="changScore"
            type="number"
            placeholder="填空题分值"
            min="0"
          />
        </el-form-item>
        <!-- 自动计算 -->
        <el-form-item label="试卷总分" prop="totalScore">
          <el-input
            v-model="form.totalScore"
            disabled
            placeholder="请输入总分"
          />
        </el-form-item>
        <el-form-item label="及格分数" prop="passLine">
          <el-input
            v-model="form.passLine"
            type="number"
            min="0"
            placeholder="请输入及格分数"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <!-- 选择题库弹框 -->
    <el-dialog width="1000px" :visible.sync="open3" :title="title3">
      <el-row :gutter="24">
        <el-col :span="4">
          <div>
            <el-tree
              :data="quesCateOptions"
              show-checkbox
              node-key="id"
              :default-expanded-keys="[2, 3]"
              :default-checked-keys="[5]"
              :props="defaultProps"
            >
            </el-tree>
          </div>
        </el-col>
        <el-col :span="20" class="multiple">
          <el-table v-loading="loading" :data="questionList" :border="true">
            <el-table-column
              label="题库名称"
              prop="nickName"
              align="center"
              :show-overflow-tooltip="true"
              width="160"
            >
            </el-table-column>
            <el-table-column
              align="center"
              prop="nickName"
              label="数量"
              width="160"
            />
            <el-table-column
              align="center"
              prop="nickName"
              label="单选"
              width="160"
            />
            <el-table-column
              label="多选"
              prop="dept.deptName"
              align="center"
              width="150"
            ></el-table-column>
            <el-table-column
              label="判断"
              prop="userName"
              align="center"
              :show-overflow-tooltip="true"
              width="150"
            />
            <el-table-column
              label="填空"
              prop="userName"
              align="center"
              :show-overflow-tooltip="true"
              width="150"
            />
          </el-table>
        </el-col>
      </el-row>
    </el-dialog>
    <!-- 查看试题 -->
    <el-dialog
      :title="title2"
      :visible.sync="open2"
      width="700px"
      append-to-body
      @close="closeSee"
    >
      <div class="checktitle">
        <p>答卷时长：{{ examPaper.duration }}</p>
        <p>试题总分：{{ examPaper.totalScore }}</p>
        <p>及格线：{{ examPaper.passLine }}</p>
      </div>
      <!-- 单选 -->
      <div class="topickinds" v-if="questionList[0].title != ''">
        <p>{{ questionList[0].title }}</p>
        <div class="topic">
          <div
            v-for="item in questionList[0].children"
            :key="item.theid"
            class="topiclist"
          >
            {{ item.subject }}
            <el-radio-group class="option" disabled>
              <el-radio
                v-for="ele in item.options"
                :key="ele.val"
                :value="ele.val"
                :label="ele.val"
                >{{ele.val+'、'+ele.title}}</el-radio
              >
            </el-radio-group>
          </div>
        </div>
      </div>
      <!-- 多选 -->
      <div class="topickinds" v-if="questionList[1].title != ''">
        <p>{{ questionList[1].title }}</p>
        <div class="topic">
          <div
            v-for="item in questionList[1].children"
            :key="item.theid"
            class="topiclist"
          >
            {{ item.subject }}
            <p class="option">
              <el-checkbox-group disabled>
                <el-checkbox
                  v-for="ele in item.options"
                  :key="ele.val"
                  :label="ele.val"
                  >{{ele.val+'、'+ele.title}}</el-checkbox
                >
              </el-checkbox-group>
            </p>
          </div>
        </div>
      </div>
      <!-- 判断 -->
      <div class="topickinds" v-if="questionList[2].title != ''">
        <p>{{ questionList[2].title }}</p>
        <div class="topic">
          <div
            v-for="item in questionList[2].children"
            :key="item.theid"
            class="topiclist"
          >
            {{ item.subject }}
            <el-radio-group class="option" disabled>
              <el-radio
                v-for="ele in item.options"
                :key="ele.val"
                :value="ele.val"
                :label="ele.val"
                >{{ele.val+'、'+ele.title}}</el-radio
              >
            </el-radio-group>
          </div>
        </div>
      </div>
      <!-- 填空 -->
      <div class="topickinds" v-if="questionList[3].title != ''">
        <p>{{ questionList[3].title }}</p>
        <div class="topic">
          <div
            v-for="item in questionList[3].children"
            :key="item.theid"
            class="topiclist"
          >
            {{ item.subject }}
            <!-- <input type="text" /> 。 -->
          </div>
        </div>
      </div>
    </el-dialog>

    <!-- 固定试题 -->
    <el-dialog
      title="选择试题"
      width="800px"
      :visible.sync="open1"
      append-to-body
      class="problem"
    >
      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button
            type="primary"
            plain
            icon="el-icon-plus"
            size="mini"
            @click="addProblem"
            >添加试题</el-button
          >
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="danger"
            plain
            icon="el-icon-delete"
            size="mini"
            :disabled="multiple"
            @click="deleteProblem"
            >批量删除</el-button
          >
        </el-col>
        <!-- <right-toolbar
          :showSearch.sync="showSearch"
          @queryTable="getListPer"
        ></right-toolbar> -->
      </el-row>
      <el-table
        :data="selectionList"
        @selection-change="handleSelectionChange1"
        :border="true"
        max-height="400px"
      >
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="题型" align="center" prop="theType">
          <template slot-scope="scope">
            <span>{{ findTheType(scope.row.theType) }}</span>
          </template>
        </el-table-column>
        <el-table-column
          label="试题名称"
          prop="subject"
          align="center"
          :show-overflow-tooltip="true"
          width="404"
        />
        <el-table-column
          label="操作"
          align="center"
          class-name="small-padding fixed-width"
          fixed="right"
          width="100"
        >
          <template slot-scope="scope">
            <el-button size="mini" type="text" @click="deleteProblem(scope.row)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitProblemForm">确 定</el-button>
        <el-button @click="cancelProblem">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 添加试题 -->
    <el-dialog
      title="添加试题"
      :visible.sync="openAdd"
      width="800px"
      append-to-body
      class="problem"
    >
      <el-form :model="problemParams" ref="problemParams" :inline="true">
        <el-form-item label="题型" prop="theType">
          <el-select
            v-model="problemParams.theType"
            clearable
            placeholder="请选择"
            @change="problemQuery"
          >
            <el-option
              v-for="item in theTypeOptions"
              :key="item.id"
              :label="item.label"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="关键字" prop="keywords" style="margin-left: 20px">
          <el-input
            v-model="problemParams.keywords"
            placeholder="请输入试题名称"
            clearable
            style="width: 240px"
            @keyup.enter.native="problemQuery"
            size="small"
          />
        </el-form-item>
        <el-form-item>
          <el-button
            type="primary"
            icon="el-icon-search"
            size="mini"
            @click="problemQuery"
            >搜索</el-button
          >
          <el-button
            icon="el-icon-refresh"
            size="mini"
            @click="problemResetQuery"
            >重置</el-button
          >
        </el-form-item>
      </el-form>
      <el-table
        v-loading="problemLoading"
        :data="problemList"
        @selection-change="handleSelectionChange2"
        :border="true"
        max-height="400px"
        :row-key="getRowId"
        ref="multipleTable"
      >
        <el-table-column
          type="selection"
          :reserve-selection="true"
          width="55"
          align="center"
        />
        <el-table-column label="题型" align="center" prop="theType">
          <template slot-scope="scope">
            <span>{{ findTheType(scope.row.theType) }}</span>
          </template>
        </el-table-column>
        <el-table-column
          label="试题名称"
          prop="subject"
          align="center"
          :show-overflow-tooltip="true"
          width="404"
        />
      </el-table>
      <pagination
        v-show="problemTotal > 0"
        :total="problemTotal"
        :page.sync="problemParams.currentPage"
        :limit.sync="problemParams.pagesize"
        @pagination="getProblemList"
        :pager-count="5"
      />
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitAddProblem">确 定</el-button>
        <el-button @click="cancelAddProblem">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import UploadImage from "@/components/ImageUpload";

import {
  listData,
  getData,
  delData,
  addData,
  updateData,
  delMultiData,
  getSelect,
  getEnable,
  questbank,
  getPaper,
} from "@/api/check/problemSet";
import { getDict, getQuestionNumOfType } from "@/api/select";
import { listData as ProblemListData } from "@/api/check/problemBaseAdmin";
export default {
  name: "problemSet",
  data() {
    var validate1 = (rule, value, callback) => {
      if (value > this.numOfType["1"]) {
        callback(new Error("题目数量不能超过" + this.numOfType["1"] + "道"));
      } else {
        callback();
      }
    };
    var validate2 = (rule, value, callback) => {
      if (value > this.numOfType["2"]) {
        callback(new Error("题目数量不能超过" + this.numOfType["2"] + "道"));
      } else {
        callback();
      }
    };
    var validate3 = (rule, value, callback) => {
      if (value > this.numOfType["3"]) {
        callback(new Error("题目数量不能超过" + this.numOfType["3"] + "道"));
      } else {
        callback();
      }
    };
    var validate4 = (rule, value, callback) => {
      if (value > this.numOfType["4"]) {
        callback(new Error("题目数量不能超过" + this.numOfType["4"] + "道"));
      } else {
        callback();
      }
    };
    var validate5 = (rule, value, callback) => {
      if (!value) {
        return callback(new Error("及格分数不能为空"));
      }
      if (value > this.form.totalScore) {
        //及格分数>=试卷总分
        callback(new Error("及格分数不能超过" + this.form.totalScore + "分"));
      } else {
        callback();
      }
    };
    return {
      treeOptions: [],
      questionList: [],
      theTypeOptions: [], //题型
      quesCateOptions: [], //试题分类
      queryParams: {
        currentPage: 1,
        pagesize: 10,
        category: undefined,
        theType: undefined,
        keywords: undefined,
      },
      showSearch: true,
      loading: true,
      tableList: [],
      total: 0,
      title: "",
      form: {},
      numOfType: null,
      rules: {
        title: [
          { required: true, message: "试卷名称不能为空", trigger: "blur" },
        ],
        radio: [
          { required: true, message: "请选择试卷类型", trigger: "change" },
        ],
        duration: [
          { required: true, message: "答卷时长不能为空", trigger: "blur" },
        ],
        typeVal: [
          { required: true, message: "请选择试卷类型", trigger: "change" },
        ],
        singleNum: [{ validator: validate1, trigger: "change" }],
        multipleNum: [{ validator: validate2, trigger: "change" }],
        judgNum: [{ validator: validate3, trigger: "change" }],
        completionNum: [{ validator: validate4, trigger: "change" }],
        passLine: [{ validator: validate5, trigger: "change" }],
        /* singleNum: [
          { required: true, message: "单选题数量和分值不能为空", trigger: "blur" },
        ],
        multipleNum: [
          { required: true, message: "多选题数量和分值不能为空", trigger: "blur" },
        ],
        judgNum: [
          { required: true, message: "判断题数量和分值不能为空", trigger: "blur" },
        ],
        completionNum: [
          { required: true, message: "填空题数量和分值不能为空", trigger: "blur" },
        ], */
        /* passLine: [
          { required: true, message: "及格分数不能为空", trigger: "blur" },
        ], */
      },

      data: [
        {
          id: 1,
          label: "一级 1",
          children: [
            {
              id: 4,
              label: "二级 1-1",
              children: [
                {
                  id: 9,
                  label: "三级 1-1-1",
                },
                {
                  id: 10,
                  label: "三级 1-1-2",
                },
              ],
            },
          ],
        },
        {
          id: 2,
          label: "一级 2",
          children: [
            {
              id: 5,
              label: "二级 2-1",
            },
            {
              id: 6,
              label: "二级 2-2",
            },
          ],
        },
        {
          id: 3,
          label: "一级 3",
          children: [
            {
              id: 7,
              label: "二级 3-1",
            },
            {
              id: 8,
              label: "二级 3-2",
            },
          ],
        },
      ],
      defaultProps: {
        children: "children",
        label: "label",
      },
      radio: "1",
      checkList: ["选中且禁用", "复选框 A"],
      title1: "",
      title2: "查看",
      title3: "选择题库",

      open3: false,
      open: false,
      singleNum: 0,

      // 添加、修改 组卷规则
      paperRules: [
        { problemNum: 0, problemScore: 0 },
        { problemNum: 0, problemScore: 0 },
        { problemNum: 0, problemScore: 0 },
        { problemNum: 0, problemScore: 0 },
      ],
      // 固定试题
      ids: [],
      single: true,
      multiple: true,
      open1: false,
      selectionList: [],

      // 添加试题
      openAdd: false,
      problemLoading: false,
      problemParams: {
        currentPage: 1,
        pagesize: 10,
        category: undefined,
        theType: undefined,
        keywords: undefined,
      },
      problemTotal: 0,
      problemList: [],
      selection: [],

      // 查看试卷
      open2: false,
      examPaper: {},
      questionList: [
        { title: "", children: [] },
        { title: "", children: [] },
        { title: "", children: [] },
        { title: "", children: [] },
      ],
    };
  },
  computed: {},
  watch: {},
  components: { UploadImage, Treeselect },
  created() {
    this.getList();
    this.getSelect();
    this.getquestbank();
    getDict(18, 0).then((response) => {
      //18-试题分类
      this.treeOptions = response.result.data;
      console.log(this.treeOptions);
    });
  },
  methods: {
    getList() {
      this.loading = true;
      listData(this.queryParams).then((response) => {
        this.tableList = response.result.rows;
        this.total = response.result.total;
        this.loading = false;
      });
    },
    getquestbank() {
      questbank(this.queryParams).then((response) => {
        this.questionList = response.result.rows;
        // this.total = response.result.total;
      });
    },
    getSelect() {
      getSelect().then((response) => {
        this.theTypeOptions = response.result.questionType; //题型
        this.quesCateOptions = response.result.questionsCategory; //试题分类
      });
    },
    handleQuery() {
      this.queryParams.currentPage = 1;
      this.getList();
    },
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "设置试卷";
    },
    handleUpdate(row) {
      this.reset();
      const theId = row.theid;
      getData(theId).then((response) => {
        // this.form = response.result;
        // 拼接清空的数据，防止数据没有定义（如添加时没有设置题目数量，修改获取数据也没有此题目）
        this.form = Object.assign(this.form, response.result);
        if (response.result.questionCategoryId===0) this.form.questionCategoryId = undefined
        // 设置固定试题默认选中数据
        this.selectionList = response.result.questionListAll;
        // 设置规则 题目数量与分值
        const rules = JSON.parse(response.result.rules);
        console.log("response---", response);
        rules.forEach((item) => {
          if (item.label === "单选") {
            this.$set(this.form, "singleNum", item.problemNum);
            this.$set(this.form, "singleVal", item.problemScore);
          } else if (item.label === "多选") {
            this.$set(this.form, "multipleNum", item.problemNum);
            this.$set(this.form, "multipleVal", item.problemScore);
          } else if (item.label === "判断") {
            this.$set(this.form, "judgNum", item.problemNum);
            this.$set(this.form, "judgVal", item.problemScore);
          } else if (item.label === "填空") {
            this.$set(this.form, "completionNum", item.problemNum);
            this.$set(this.form, "completionVal", item.problemScore);
          }
        });
        this.open = true;
        this.title = "修改";
      });
    },
    submitForm() {
      console.log("this.form", this.form);
      let result = this.getRules();
      this.$set(this.form, "rules", JSON.stringify(result)); //试卷规则
      this.changNum();
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.form.theid != undefined) {
            updateData(this.form).then((response) => {
              this.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addData(this.form).then((response) => {
              this.msgSuccess("添加成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    cancel() {
      this.open = false;
      this.reset();
    },
    reset() {
      this.form = {
        singleNum: 0,
        singleVal: 0,
        multipleNum: 0,
        multipleVal: 0,
        judgNum: 0,
        judgVal: 0,
        completionNum: 0,
        completionVal: 0,
        title: undefined, //试卷名称
        typeVal: 1, // 试卷类型
        theNum: undefined, //试题数量
        duration: undefined, //试卷考试时长
        totalScore: 0, //试卷总分
        passLine: undefined, //试卷及格线
        publisherId: this.$store.state.userInfo.theid, //发布人id
        publisher: this.$store.state.userInfo.thename, //发布人
        questionCategoryId: undefined, //试题分类 id
        questionCategory: undefined, //试题分类
        paperContent: undefined, //试卷内容（如果 试卷类型 是 固定试题 时使用，直接存放具体题目）
      };
      this.resetForm("form");
      this.selectionList = [];
      // 获取试题数量限制  默认获取全部试题数量（试题分类传undefined）
      this.inputTree(this.form.questionCategoryId);
    },
    handleDelete(row) {
      const theId = row.theid || this.ids;
      this.$confirm("是否确认删除?", "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(function () {
          // 调接口
          return delData(theId);
        })
        .then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        });
    },
    handleStatusChange(row) {
      console.log("row--", row);
      let text = row.enable === 1 ? "启用" : "停用";
      this.$confirm("是否确认" + text + '"?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(function () {
          // 调接口 改变状态值
          return getEnable(row.theid, row.enable);
        })
        .then(() => {
          this.msgSuccess(text + "成功");
        })
        .catch(function () {
          row.enable = row.enable === 0 ? 1 : 0;
        });
    },
    // 选择试卷类型
    changeTypeVal(val) {
      console.log("试卷类型--", val);
      // this.resetProblem()
      // this.$set(this.form, "typeVal", val);
      // 试卷类型 1-随机试题 2-固定试题
      /* if(val===2) {
        this.open1 = true;  //打开固定试题-弹框
        console.log('打开固定试题-this.selectionList--',this.selectionList)
        this.findTheTypeProblem()
        // this.getProblemList()
      } */
    },
    handleColumnsConfig() {
      // this.resetProblem()
      this.$set(this.form, "typeVal", 2);
      this.open1 = true; //打开固定试题-弹框
      console.log("打开固定试题-this.selectionList--", this.selectionList);
      this.findTheTypeProblem();
    },
    // 固定试题-弹框
    // 添加试题
    addProblem() {
      this.openAdd = true;
      /* if (this.form.theid) {  //修改打开的
        let listData = [] //当前的table的数据
        // let hasSelectList = [] //已经选择的id组成的数组
        let hasSelectList = [2720,2719,2716] //已经选择的id组成的数组
        // let params = { category: this.form.questionCategoryId }
        let params = {  }
        ProblemListData(params).then((response) => {
          console.log('试题所有数据---',response.result.rows)
          listData = response.result.rows;
          listData.forEach(row => {
            if(hasSelectList.indexOf(row.theid) >= 0){
              this.$refs.multipleTable.toggleRowSelection(row,true);
            }
          })
        });
        console.log('修改--------------------------------')
      }else {
        console.log('添加--------------------------------',this.selectionList)
        this.selectionList.forEach(item => {
          this.$refs.multipleTable.toggleRowSelection(item, true)
        })
      } */
      this.problemLoading = true;
      this.problemParams.category = this.form.questionCategoryId;
      console.log("this.problemParams.category--", this.problemParams.category);
      ProblemListData(this.problemParams).then((response) => {
        this.problemList = response.result.rows;
        this.problemTotal = response.result.total;
        this.selectionList.forEach((item) => {
          this.$refs.multipleTable.toggleRowSelection(item, true);
        });
        this.problemLoading = false;
      });

      console.log("添加--", JSON.stringify(this.selectionList));
      // this.getProblemList()
    },
    // 获取试题
    getProblemList() {
      this.problemLoading = true;
      this.problemParams.category = this.form.questionCategoryId;
      console.log(
        "this.form.questionCategoryId--",
        this.form.questionCategoryId
      );
      ProblemListData(this.problemParams).then((response) => {
        this.problemList = response.result.rows;
        this.problemTotal = response.result.total;
        this.problemLoading = false;
      });
    },
    problemQuery() {
      this.problemParams.currentPage = 1;
      this.getProblemList();
    },
    problemResetQuery() {
      this.resetForm("problemParams");
      this.problemQuery();
    },
    handleSelectionChange2(selection) {
      console.log("selection---", selection);
      this.selection = selection;
    },
    // 添加试题-弹框-确定
    submitAddProblem() {
      this.selectionList = this.selection;
      this.$refs.multipleTable.clearSelection();
      this.openAdd = false;
    },
    // 添加试题-弹框-取消
    cancelAddProblem() {
      this.$refs.multipleTable.clearSelection();
      this.openAdd = false;
    },
    // 多选框选中数据
    handleSelectionChange1(selection) {
      this.ids = selection.map((item) => item.theid);
      this.single = selection.length != 1;
      this.multiple = !selection.length;
    },
    // 批量删除/删除
    deleteProblem(row) {
      let _this = this;
      const theId = row.theid;
      if (row.theid) {
        //删除
        this.$confirm("是否确认删除?", "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }).then(function () {
          _this.selectionList = _this.selectionList.filter((item) => {
            return item.theid != theId;
          });
          _this.msgSuccess("删除成功");
        });
      } else {
        //批量删除
        this.$confirm("是否确认删除?", "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }).then(function () {
          let newArr = [],
            flag = true;
          _this.selectionList.forEach((item) => {
            // 遍历每一个元素 判断当前元素，是否是要删除的元素
            // 把所有不需要删除的元素找到
            flag = _this.ids.some((id) => {
              return item.theid === id; //只要一个为turn,就会返回true 为true，说明是要删除的元素 为false，说明要保留的元素
            });
            if (flag === false) {
              newArr.push(item);
            }
          });
          _this.selectionList = newArr;
          _this.msgSuccess("删除成功");
        });
      }
    },
    // 固定试题-弹框-确定
    submitProblemForm() {
      if (this.theTypeOptions.length > 0) {
        this.findTheTypeProblem();
      } else {
        return this.msgError("请先添加题型!");
      }

      this.open1 = false;
    },
    // 固定试题-弹框-取消
    cancelProblem() {
      this.open1 = false;
    },
    // 试题数组--根据题型过滤
    findTheTypeProblem() {
      // concat() s深拷贝该方法不会改变现有的数组，而仅仅会返回被连接数组的一个副本。
      // let result = this.theTypeOptions.concat();
      // let result = this.theTypeOptions.map(item => {
      //   let obj = {...item, checked: false}
      //   return obj
      // })
      let result = JSON.parse(JSON.stringify(this.theTypeOptions)); //数组是引用类型, 深拷贝一下

      result.map((e) => {
        delete e.value;
        delete e.tid;
        delete e.sid;
      }); //然后删除属性title
      console.log("result-1--", result);

      let filterArr = [];
      let idStr = "";
      if (result.length > 0) {
        result.forEach((item) => {
          filterArr = this.selectionList.filter((ele) => {
            console.log("ele.theType--", ele.theType);
            console.log("item.id--", item.id);
            return ele.theType === item.id;
          });
          this.$set(item, "problemNum", filterArr.length);
          idStr = filterArr.map((e) => e.theid).join(",");
          this.$set(item, "idListStr", idStr);
        });
        console.log("result-2--", result);
        this.$set(this.form, "singleNum", result[0].problemNum);
        this.$set(this.form, "multipleNum", result[1].problemNum);
        this.$set(this.form, "judgNum", result[2].problemNum);
        this.$set(this.form, "completionNum", result[3].problemNum);
        // 题目数量改变 总分随之改变
        this.changScore();
        let resultNew = result.filter((item) => {
          return item.problemNum > 0;
        });
        this.$set(this.form, "paperContent", JSON.stringify(resultNew)); //试卷内容
      }
      return result;
    },
    // 清空题目、分数值
    resetProblem() {
      this.form = {
        singleNum: 0,
        singleVal: 0,
        multipleNum: 0,
        multipleVal: 0,
        judgNum: 0,
        judgVal: 0,
        completionNum: 0,
        completionVal: 0,
        totalScore: 0, //试卷总分
      };
    },
    // 查看试卷
    handleSee(row) {
      const theId = row.theid;
      getData(theId).then((response) => {
        this.examPaper = response.result;
        let obj = response.result.questionList;

        // let obj = JSON.parse(JSON.stringify(response.result.questionList))
        let questionList = [
          { title: "", children: [] },
          { title: "", children: [] },
          { title: "", children: [] },
          { title: "", children: [] },
        ];
        Object.keys(obj).forEach((key) => {
          if (
            obj[key].title.indexOf("单选题") != -1 &&
            obj[key].children.length > 0
          ) {
            questionList[0] = obj[key];
          } else if (
            obj[key].title.indexOf("多选题") != -1 &&
            obj[key].children.length > 0
          ) {
            questionList[1] = obj[key];
          } else if (
            obj[key].title.indexOf("判断题") != -1 &&
            obj[key].children.length > 0
          ) {
            questionList[2] = obj[key];
          } else if (
            obj[key].title.indexOf("填空题") != -1 &&
            obj[key].children.length > 0
          ) {
            questionList[3] = obj[key];
          }
        });
        this.questionList = questionList;
        console.log("this.examPaper--", this.examPaper.questionList);
      });
      this.open2 = true;
    },
    // 关闭查看试卷
    closeSee() {
      this.examPaper = {};
      this.questionList = [
        { title: "", children: [] },
        { title: "", children: [] },
        { title: "", children: [] },
        { title: "", children: [] },
      ];
    },
    // 选择题库
    Multiple() {
      this.open3 = true;
    },
    changScore() {
      console.log("changScore----------");
      let val1 = Number(this.form.singleVal) * Number(this.form.singleNum),
        val2 = Number(this.form.multipleVal) * Number(this.form.multipleNum),
        val3 = Number(this.form.judgVal) * Number(this.form.judgNum),
        val4 =
          Number(this.form.completionVal) * Number(this.form.completionNum);
      let totalScore = val1 + val2 + val3 + val4;
      this.$set(this.form, "totalScore", totalScore);
    },
    changNum() {
      let val1 = Number(this.form.singleNum),
        val2 = Number(this.form.multipleNum),
        val3 = Number(this.form.judgNum),
        val4 = Number(this.form.completionNum);
      let theNum = val1 + val2 + val3 + val4;
      this.$set(this.form, "theNum", theNum);
      // this.form.totalScore = val1 + val2 + val3 + val4
    },
    // 试题数组--根据题型过滤
    getRules() {
      let result = [
        {
          id: 1,
          label: "单选",
          problemNum: Number(this.form.singleNum),
          problemScore: Number(this.form.singleVal),
          idListStr: ""
        },
        {
          id: 2,
          label: "多选",
          problemNum: Number(this.form.multipleNum),
          problemScore: Number(this.form.multipleVal),
          idListStr: ""
        },
        {
          id: 3,
          label: "判断",
          problemNum: Number(this.form.judgNum),
          problemScore: Number(this.form.judgVal),
          idListStr: ""
        },
        {
          id: 4,
          label: "填空",
          problemNum: Number(this.form.completionNum),
          problemScore: Number(this.form.completionVal),
          idListStr: ""
        },
      ];
      let resultNew = result.filter((item) => {
        return item.problemNum > 0;
      });
      console.log('this.form.paperContent-----',this.form.paperContent)
      if(this.form.typeVal === 1) {  //随机试题，没有题目串
        resultNew.forEach((item, index) => {
          this.$set(item, "idListStr", '');
        })
      }else if(this.form.typeVal === 2) {  //是固定试题，有题目串
        let paperContentList = JSON.parse(this.form.paperContent)
        resultNew.forEach((item, index) => {
          this.$set(item, "idListStr", paperContentList[index].idListStr);
        })
      }
      console.log("result--组卷规则----", resultNew);
      return resultNew;
    },
    // 跳转子页面
    handleTestPaper(row) {
      const userId = row.userId || this.ids;
      this.$router.push({ path: "problemTest", query: { id: row.deptId } });
    },
    selectTree(val) {
      if (this.treeOptions.length > 0) {
        this.form.questionCategory = val.label;
      }
      // 切换试题分类 展示对应试题分类题目
      this.form.singleNum = 0
      this.form.singleVal = 0
      this.form.multipleNum = 0
      this.form.multipleVal = 0
      this.form.judgNum = 0
      this.form.judgVal = 0
      this.form.completionNum = 0
      this.form.completionVal = 0
      this.form.theNum = 0
      this.form.totalScore = 0
      this.selectionList = [];
    },
    inputTree(val) {
      console.log("val--", val);
      if (this.treeOptions.length > 0) {
        getQuestionNumOfType(val).then((res) => {
          this.numOfType = res.result.numOfType;
          console.log("this.numOfType--", this.numOfType);
        });
      }
    },
    findTheType(val) {
      if (this.theTypeOptions.length > 0) {
        let value = val
          ? this.theTypeOptions.find((ele) => ele.id === val).label
          : "";
        return value;
      }
    },

    // 过滤
    getRowId(row) {
      return row.theid;
    },
    // 全选/全不选
    selectAll(selection) {
      console.log("selection---", selection);
    },
  },
};
</script>

<style scoped lang="scss">
.judge {
  margin-top: 10px;
}
.checktitle {
  width: 100%;
  display: flex;
  font-size: 15px;
  color: red;
  margin-bottom: 20px;
  border-bottom: 1px solid red;
  padding-bottom: 10px;
  p {
    margin-right: 10%;
  }
}
.multiple {
  margin: 0;
  ::v-deep .el-table {
    margin-top: 0;
  }
}
.side {
  position: relative;
}
.side /deep/ .el-input {
  width: 48%;
}
.side /deep/ .el-input:last-child {
  position: absolute;
  right: 0;
}
.el-table .active {
  color: #409eff;
  cursor: pointer;
  text-decoration: underline;
}
// 查看试题
.topickinds {
  margin-bottom: 20px;
  .topic {
    margin-top: 20px;
    .topiclist {
      margin-top: 20px;
      input {
        border-bottom: 1px solid;
      }
    }
    .option {
      margin-top: 20px;
      display: block;
    }
  }
}

// 固定试题
.problem /deep/ .el-table {
  margin-top: 0;
}

.form-div /deep/ .side .el-input:nth-child(2) {
  position: absolute;
  right: 0;
}

// 查看试卷  禁用之后样式修改
.topickinds .topic .option {
  display: block;
}
/deep/ .el-radio__input.is-disabled + span.el-radio__label {
  color: #606266;
  cursor: not-allowed;
}
/deep/ .el-radio__input.is-disabled .el-radio__inner,
.el-radio__input.is-disabled.is-checked .el-radio__inner {
  background-color: #fff;
  border-color: #dcdfe6;
}
/deep/ .el-checkbox__input.is-disabled + span.el-checkbox__label {
  color: #606266;
  cursor: not-allowed;
}
</style>
